﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Framework.Constructor.Sql
{
    public class ObjetoBase
    {
        public Int32 Id { get; set; }
        public String Name { get; set; }
        public Int32 Object_Id { get { return this.Id; } set { this.Id = value; } }

        public ObjetoBase( Dictionary<String, Object> diccionario )
        {
            foreach ( PropertyInfo pi in this.GetType().GetProperties() )
            {
                foreach ( KeyValuePair<String, Object> parametro in diccionario )
                {
                    if ( pi.Name.ToLowerInvariant() == parametro.Key.ToLowerInvariant() )
                    {
                        pi.SetValue( this, Convert.ChangeType( parametro.Value, pi.PropertyType ), null );
                    }
                }
            }
        }

        public override string ToString()
        {
            return this.Name;
        }

        public virtual String ToXmlString(String espaciado)
        {
            String nameSpace = String.Format( "Framework.Modelo.Sql.{0}", this.GetType().Name );
            StringBuilder sb = new StringBuilder();
            sb.Append( String.Format( "{0}<{1}>", espaciado, nameSpace ) );
            sb.Append( Environment.NewLine );
            foreach ( PropertyInfo pi in this.GetType().GetProperties() )
            {
                if ( !pi.PropertyType.Name.Contains("Collection" ))
                {
                    sb.Append( String.Format( "{0}\t<{1} type=\"{2}\">", espaciado, pi.Name, pi.PropertyType.FullName ) );
                    sb.Append( Environment.NewLine );
                    if ( pi.PropertyType.FullName.Contains( "Framework.Modelo.Sql" ) )
                    {
                        sb.Append( ((ObjetoBase)pi.GetValue( this, null )).ToXmlString( espaciado + "\t" ) );
                        sb.Append( Environment.NewLine );
                    }
                    else
                    {
                        sb.Append( espaciado + "\t\t" );
                        sb.Append( pi.GetValue( this, null ).ToString() );
                        sb.Append( Environment.NewLine );
                    }
                    sb.Append( String.Format( "{0}\t</{1}>", espaciado, pi.Name ) );
                    sb.Append( Environment.NewLine );
                }
            }
            sb.Append( this.ToXmlStringChilds(espaciado+"\t") );
            sb.Append( String.Format( "{0}</{1}>", espaciado, nameSpace ) );
            return sb.ToString();
        }

        public virtual String ToXmlStringChilds( String espaciado )
        {
            return String.Empty;
        }
    }
}
